<template>
  <div class="contract-applications-container">
    <!-- 背景装饰元素 -->
    <div class="background-decoration">
      <div class="floating-shape shape-1"></div>
      <div class="floating-shape shape-2"></div>
      <div class="floating-shape shape-3"></div>
      <div class="floating-shape shape-4"></div>
    </div>

    <div class="applications-wrapper">
      <!-- 页面标题 -->
      <div class="header-section">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <h2 class="page-title">签约申请管理</h2>
        <el-button @click="refreshApplications" icon="Refresh" :loading="loading">刷新</el-button>
      </div>

      <!-- 统计信息 -->
      <div class="stats-section">
        <div class="stat-card">
          <div class="stat-value">{{ applications.length }}</div>
          <div class="stat-label">总申请数</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ pendingCount }}</div>
          <div class="stat-label">待处理</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ approvedCount }}</div>
          <div class="stat-label">已同意</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ rejectedCount }}</div>
          <div class="stat-label">已拒绝</div>
        </div>
      </div>

      <!-- 申请列表 -->
      <div class="applications-content">
        <div v-if="loading" class="loading-container" v-loading="loading" element-loading-text="正在加载申请列表...">
          <div style="height: 400px; background: rgba(255, 255, 255, 0.9); border-radius: 15px;"></div>
        </div>

        <div v-else-if="applications.length === 0" class="empty-state">
          <el-empty description="暂无签约申请" />
        </div>

        <div v-else class="applications-list">
          <div
              v-for="application in applications"
              :key="application.contractId"
              class="application-card"
          >
            <div class="card-header">
              <div class="tenant-info">
                <el-avatar :size="50" :src="application.tenant?.avatar || '/default-avatar.png'" />
                <div class="tenant-details">
                  <h3>{{ application.tenant?.realName || '租客' }}</h3>
                  <p>{{ application.tenant?.phone || '暂无联系方式' }}</p>
                </div>
              </div>
              <div class="status-badge">
                <el-tag
                    :type="getStatusType(application.signStatus)"
                    size="large"
                >
                  {{ getStatusText(application.signStatus) }}
                </el-tag>
              </div>
            </div>

            <div class="card-content">
              <div class="house-info">
                <h4>房源信息</h4>
                <p><strong>房源ID:</strong> {{ application.house?.houseId }}</p>
                <p><strong>地址:</strong> {{ application.house?.houseLocation || '暂无地址' }}</p>
              </div>

              <div class="contract-details">
                <h4>合同详情</h4>
                <div class="details-grid">
                  <div class="detail-item">
                    <span class="label">租赁期间:</span>
                    <span class="value">{{ formatDate(application.startDate) }} - {{ formatDate(application.endDate) }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">月租金:</span>
                    <span class="value">¥{{ application.monthRent }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">押金:</span>
                    <span class="value">¥{{ application.deposit }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">支付方式:</span>
                    <span class="value">{{ getPaymentTypeText(application.paymentType) }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">申请时间:</span>
                    <span class="value">{{ formatDateTime(application.applyTime) }}</span>
                  </div>
                </div>
              </div>

              <div v-if="application.refuseReason" class="refuse-reason">
                <h4>拒绝原因</h4>
                <p>{{ application.refuseReason }}</p>
              </div>
            </div>

            <div class="card-actions" v-if="application.signStatus === 0">
              <el-button
                  type="success"
                  @click="approveApplication(application)"
                  :loading="processing === application.contractId"
              >
                同意申请
              </el-button>
              <el-button
                  type="danger"
                  @click="showRejectDialog(application)"
                  :loading="processing === application.contractId"
              >
                拒绝申请
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 拒绝申请对话框 -->
    <el-dialog
        v-model="showRejectDialogVisible"
        title="拒绝签约申请"
        width="500px"
        :before-close="handleRejectDialogClose"
    >
      <el-form
          ref="rejectFormRef"
          :model="rejectForm"
          :rules="rejectRules"
          label-width="100px"
      >
        <el-form-item label="拒绝原因" prop="reason">
          <el-input
              v-model="rejectForm.reason"
              type="textarea"
              :rows="4"
              placeholder="请输入拒绝原因"
              maxlength="200"
              show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRejectDialogVisible = false" :disabled="rejecting">取消</el-button>
          <el-button
              type="danger"
              @click="confirmReject"
              :loading="rejecting"
          >
            确认拒绝
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { ArrowLeft, Refresh } from '@element-plus/icons-vue'

const router = useRouter()

// 临时信息值，用于API请求头
const TEMP_INFO_VALUE = '9fbf0bf9-350d-4fad-8799-acfbfa3dd579'

// 创建带有默认请求头的 axios 实例
const apiClient = axios.create({
  headers: {
    'info': TEMP_INFO_VALUE
  }
})

// 响应式数据
const loading = ref(false)
const processing = ref(null)
const applications = ref([])
const showRejectDialogVisible = ref(false)
const rejectFormRef = ref()
const rejecting = ref(false)
const currentApplication = ref(null)

// 拒绝表单
const rejectForm = ref({
  reason: ''
})

// 拒绝表单验证规则
const rejectRules = {
  reason: [
    { required: true, message: '请输入拒绝原因', trigger: 'blur' },
    { min: 5, message: '拒绝原因至少5个字符', trigger: 'blur' }
  ]
}

// 计算属性
const pendingCount = computed(() => applications.value.filter(app => app.signStatus === 0).length)
const approvedCount = computed(() => applications.value.filter(app => app.signStatus === 1).length)
const rejectedCount = computed(() => applications.value.filter(app => app.signStatus === 2).length)

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'warning',  // 待处理
    1: 'success',  // 已同意
    2: 'danger'    // 已拒绝
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待处理',
    1: '已同意',
    2: '已拒绝'
  }
  return statusMap[status] || '未知状态'
}

// 获取支付方式文本
const getPaymentTypeText = (type) => {
  const typeMap = {
    1: '月付',
    2: '季付',
    3: '年付'
  }
  return typeMap[type] || '未知'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未设置'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return '未设置'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 获取签约申请列表
const fetchApplications = async () => {
  loading.value = true
  try {
    const response = await apiClient.get('/housingHub/contract/landlord/applications')
    
    if (response.data.code === 200 || response.data.code === '200') {
      applications.value = response.data.data || []
      console.log('获取到的申请列表:', applications.value)
    } else {
      throw new Error(response.data.message || '获取申请列表失败')
    }
  } catch (error) {
    console.error('获取申请列表失败:', error)
    ElMessage.error('获取申请列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 刷新申请列表
const refreshApplications = () => {
  fetchApplications()
}

// 同意申请
const approveApplication = async (application) => {
  try {
    await ElMessageBox.confirm(
        '确定要同意这个签约申请吗？',
        '确认操作',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    processing.value = application.contractId

    const verifyData = {
      contractId: application.contractId,
      signStatus: 1
    }

    const response = await apiClient.post('/housingHub/contract/landlord/verify', verifyData)

    if (response.data.code === 200 || response.data.code === '200') {
      ElMessage.success('签约申请已同意')
      // 更新本地状态
      application.signStatus = 1
    } else {
      throw new Error(response.data.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('同意申请失败:', error)
      ElMessage.error(error.message || '操作失败，请稍后重试')
    }
  } finally {
    processing.value = null
  }
}

// 显示拒绝对话框
const showRejectDialog = (application) => {
  currentApplication.value = application
  rejectForm.value.reason = ''
  showRejectDialogVisible.value = true
}

// 关闭拒绝对话框
const handleRejectDialogClose = (done) => {
  if (rejecting.value) {
    ElMessage.warning('正在处理中，请稍候...')
    return
  }
  done()
}

// 确认拒绝
const confirmReject = async () => {
  if (!rejectFormRef.value) {
    ElMessage.error('表单引用不存在')
    return
  }

  rejectFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请填写完整信息')
      return
    }

    rejecting.value = true

    try {
      const verifyData = {
        contractId: currentApplication.value.contractId,
        signStatus: 2,
        refuseReason: rejectForm.value.reason
      }

      const response = await apiClient.post('/housingHub/contract/landlord/verify', verifyData)

      if (response.data.code === 200 || response.data.code === '200') {
        ElMessage.success('签约申请已拒绝')
        // 更新本地状态
        currentApplication.value.signStatus = 2
        currentApplication.value.refuseReason = rejectForm.value.reason
        showRejectDialogVisible.value = false
      } else {
        throw new Error(response.data.message || '操作失败')
      }
    } catch (error) {
      console.error('拒绝申请失败:', error)
      ElMessage.error(error.message || '操作失败，请稍后重试')
    } finally {
      rejecting.value = false
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchApplications()
})
</script>

<style scoped>
.contract-applications-container {
  display: flex;
  min-height: 100vh;
  overflow: hidden;
  position: relative;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
}

.floating-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 15s infinite linear;
}

.shape-1 {
  width: 200px;
  height: 200px;
  top: -50px;
  left: -50px;
  animation-duration: 20s;
  background: radial-gradient(circle, rgba(74, 144, 226, 0.2) 0%, transparent 70%);
}

.shape-2 {
  width: 150px;
  height: 150px;
  bottom: -40px;
  right: -40px;
  animation-duration: 25s;
  animation-direction: reverse;
  background: radial-gradient(circle, rgba(255, 107, 107, 0.2) 0%, transparent 70%);
}

.shape-3 {
  width: 100px;
  height: 100px;
  top: 30%;
  right: 20%;
  animation-duration: 15s;
  background: radial-gradient(circle, rgba(80, 227, 194, 0.2) 0%, transparent 70%);
}

.shape-4 {
  width: 120px;
  height: 120px;
  bottom: 20%;
  left: 20%;
  animation-duration: 18s;
  animation-direction: reverse;
  background: radial-gradient(circle, rgba(255, 209, 102, 0.2) 0%, transparent 70%);
}

@keyframes float {
  0% {
    transform: translate(0, 0) rotate(0deg);
  }
  25% {
    transform: translate(20px, 20px) rotate(90deg);
  }
  50% {
    transform: translate(0, 40px) rotate(180deg);
  }
  75% {
    transform: translate(-20px, 20px) rotate(270deg);
  }
  100% {
    transform: translate(0, 0) rotate(360deg);
  }
}

.applications-wrapper {
  width: 100%;
  max-width: 1400px;
  margin: 20px auto;
  z-index: 1;
  position: relative;
  padding: 0 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.header-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.header-section .el-button {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
}

.header-section .el-button:hover {
  background: rgba(255, 255, 255, 0.3);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  letter-spacing: 1px;
  flex: 1;
  text-align: center;
}

.stats-section {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 15px;
  padding: 20px;
  text-align: center;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #409EFF;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
}

.applications-content {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 15px;
  padding: 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
  min-height: 400px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.applications-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.application-card {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #eee;
  transition: all 0.3s ease;
}

.application-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.tenant-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.tenant-details h3 {
  margin: 0 0 5px;
  font-size: 18px;
  color: #2c3e50;
}

.tenant-details p {
  margin: 0;
  font-size: 14px;
  color: #7f8c8d;
}

.card-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.house-info h4,
.contract-details h4,
.refuse-reason h4 {
  margin: 0 0 10px;
  font-size: 16px;
  color: #2c3e50;
  font-weight: 600;
}

.house-info p {
  margin: 5px 0;
  font-size: 14px;
  color: #7f8c8d;
}

.details-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.detail-item .label {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
}

.detail-item .value {
  color: #7f8c8d;
  font-size: 14px;
}

.refuse-reason {
  background: #fef0f0;
  border: 1px solid #fbc4c4;
  border-radius: 8px;
  padding: 15px;
}

.refuse-reason p {
  margin: 0;
  color: #e74c3c;
  font-size: 14px;
  line-height: 1.5;
}

.card-actions {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 992px) {
  .stats-section {
    flex-direction: column;
  }

  .details-grid {
    grid-template-columns: 1fr;
  }

  .card-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .card-actions {
    flex-direction: column;
  }
}
</style>
